<template>
  <div>
    <el-form ref="ruleFormRef" style="width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="角色名称" prop="roleName" @change="OneUserName">
        <el-input v-model="ruleForm.roleName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          添加
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useCounterStore } from '@/stores/counter';


const store = useCounterStore();
const router = useRouter();

//姓名唯一验证状态
const Status = reactive({
  OneNameStatu: 1, //1通过名不称重复 2不通过名称重复
})



const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

const ruleForm: any = reactive({
  // "roleId": 0,
  "roleName": "",
  "createName": store.ccstore.nickName,
  // "createTime": new Date(),
  // "updateName": "",
  // "updateTime": "",
  "isDeleted": false
})


const rules = reactive<FormRules>({
  roleName: [
    { required: true, message: '角色名不可为空', trigger: 'blur' },
  ],
})



//姓名唯一验证
const OneUserName = () => {
  axios.get(`https://localhost:7174/api/Message/OneRoleName?RoleName=` + ruleForm.roleName).then(res => {

    console.log(res, "唯一验证状态码")
    if (res.data.code == 209) {
      ElMessage.error(res.data.msg)
      return Status.OneNameStatu = 2;
    } else {
      ElMessage.success(res.data.msg)
      return Status.OneNameStatu = 1;
    }
  })
}

//添加
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (Status.OneNameStatu == 2) {
        ElMessage.error("添加失败!!用户名称重复")
        return;
      }
      axios.post("https://localhost:7272/api/Message/AddRole", ruleForm).then(res => {
        if (res.data.code == 212) {
          ElMessage.success(res.data.msg);
          router.push({
            name: 'RoleList'
          })
        } else {
          ElMessage.error("添加失败");
        }
      })
    } else {
      // console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//#endregion




</script>

<style scoped></style>